package com.example.SpringBoot_demo.controller;



import com.example.SpringBoot_demo.bean.Book;
import com.example.SpringBoot_demo.bean.User;
import com.example.SpringBoot_demo.service.IBookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping()
public class BookController {
    @Autowired
    private IBookService bookService;

//    @GetMapping("viewBook")
//    public String viewBook(HttpServletRequest request){
//        System.out.println("kkkkkkkkkkkkkkkkk");
//        request.setAttribute("books",bookService.viewBook());
//        request.getAttribute("books");
//        System.out.println("vvvvvvvvvvvvvvvvvvv");
//        return "viewBook";
//    }
    @RequestMapping("/viewBook")
    public String getAllUser(Model model, @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
    PageHelper.startPage(pageNum,5);
    List<Book> list = bookService.viewBook();
    PageInfo<Book> pageInfo = new PageInfo<>(list);
    model.addAttribute("pageInfo",pageInfo);
    System.out.println();
    return "viewBook";
}

    @GetMapping("deleteBook")
    public String deleteBook(String bookId,HttpServletRequest request){
        System.out.println("正在删除书籍");
        bookService.deleteBook(bookId);
        return "redirect:viewBook";
    }

    @RequestMapping("addBook")
    public String add(){
        return "addBook";
    }

    @RequestMapping(value = "addBookSave",method = RequestMethod.POST)
    public String addUser(Model model, Book book, HttpServletRequest request){
        bookService.addBook(book);
        model.addAttribute("books",book);
        request.setAttribute("books",bookService.viewBook());
        return "redirect:viewBook";
    }

    @RequestMapping("changeBook")
    public String changeBook(Model model,String bookId){
        Book book = bookService.getBookById(bookId);
        model.addAttribute("books", book);
        return "changeBook";
    }

    @RequestMapping(value = "changeBookSave",method = RequestMethod.POST)
    public String changeBookSave(Book book){
        bookService.changeBook(book);
        return "redirect:viewBook";
    }

    @GetMapping("getBook")
    public String getUser(Model model, HttpServletRequest request,String bookId,String bookName){
        List<Book> book = bookService.getBook(bookId,bookName);
        model.addAttribute("books", book);
        request.setAttribute("pageInfo.list",book);
        return "findBook";
    }

}